package vi

var GetDemoTpl = `
package vi

import (
    "fmt"
    "github.com/hashicorp/consul/api"
    "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/trace"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
    "log"
    "net"
    "strconv"
    "{{.App}}/pkg/storage/conf"
    "{{.App}}/proto/pb"
)

var (
    Tracer trace.Tracer
)

func NewVideoHandler() *VideoHandler {
    cfg := conf.Cfg.Consul
    fmt.Println("--------------->cfg.Services:", cfg.Services[0].Name)
    Tracer = otel.Tracer(cfg.Services[0].Name)

    //从consul 获取grpc服务地址
    grpcAddr, err := discoverService(cfg.Services[0].Name, cfg.Host, cfg.Port)
    if err != nil {
        fmt.Println("获取grpc服务地址失败")
        fmt.Println(err)
    }

    if grpcAddr == "" {
        fmt.Println("grpc服务地址为空")
    }
    fmt.Println("服务器地址")
    fmt.Println(grpcAddr)
    conn, err := grpc.NewClient(
        grpcAddr,
        grpc.WithTransportCredentials(insecure.NewCredentials()),
        grpc.WithStatsHandler(otelgrpc.NewClientHandler()), // 设置 StatsHandler
        //grpc.WithChainUnaryInterceptor(clientUnaryInterceptor),
    )
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }

    return &VideoHandler{VideoClient: pb.NewVisrvClient(conn)}
}

func discoverService(serviceName string, host string, port int) (string, error) {
    config := api.DefaultConfig()
    config.Address = fmt.Sprintf("%s:%d", host, port)

    client, err := api.NewClient(config)
    if err != nil {
        return "", err
    }

    services, err := client.Agent().Services()
    if err != nil {
        return "", err
    }

    for _, service := range services {
        if service.Service == serviceName {
            return net.JoinHostPort(service.Address, strconv.Itoa(service.Port)), nil
        }
    }

    return "", nil
}
`
